import { lazy, Suspense } from 'react'
import { createBrowserRouter, Outlet } from 'react-router-dom'
import { AppRouteObject, RouteMeta } from './types'
import Layout from '@/components/Layout'
import Loading from '@/components/Loading'
import ErrorPage from '@/pages/ErrorPage'
import { AuthProvider } from '@/context/AuthContext'
import AuthGuard from './auth'

// 使用 React.lazy 实现代码分割
const Home = lazy(() => import('@/pages/Home'))
const Login = lazy(() => import('@/pages/Login'))
const Dashboard = lazy(() => import('@/pages/Dashboard'))
const User = lazy(() => import('@/pages/User'))
const Menu = lazy(() => import('@/pages/Menu'))

const routes: AppRouteObject[] = [
  {
    path: '/',
    element: (
      <AuthProvider>
        <Outlet />
      </AuthProvider>
    ),
    children: [
      {
        path: '',
        element: <Layout />,
        errorElement: <ErrorPage />,
        children: [
          {
            index: true,
            element: (
              <Suspense fallback={<Loading />}>
                <Home />
              </Suspense>
            )
          },
          {
            path: 'dashboard',
            meta: { requiresAuth: true },
            element: <Outlet />,
            children: [
              {
                index: true,
                meta: { title: '控制台' },
                element: (
                  <Suspense fallback={<Loading />}>
                    <Dashboard />
                  </Suspense>
                )
              }
            ]
          },
          {
            path: 'user',
            meta: { requiresAuth: true },
            element: (
              <Outlet />
            ),
            children: [
              {
                index: true,
                meta: { title: '用户管理' },
                element: (
                  <Suspense fallback={<Loading />}>
                    <User />
                  </Suspense>
                )
              }
            ]
          },
          {
            path: 'menu',
            meta: { requiresAuth: true },
            element: <Outlet />,
            children: [
              {
                index: true,
                meta: { title: '菜单管理' },
                element: (
                  <Suspense fallback={<Loading />}>
                    <Menu />
                  </Suspense>
                )
              }
            ]
          }
        ]
      },
      {
        path: 'login',
        element: (
          <Suspense fallback={<Loading />}>
            <Login />
          </Suspense>
        ),
        meta: { requiresAuth: false }
      },
    ]
  }
];

export const router = createBrowserRouter(routes);

export const findMetaByPath = (targetPath: string, parentPath: string = '', routeList: AppRouteObject[] = routes): RouteMeta | undefined => {
  // console.log(targetPath, routeList)
  for (const route of routeList) {
    const fullPath = route.path ? `${parentPath}/${route.path}`.replace(/\/+/g, '/') : parentPath;
    // 如果当前路由的 fullPath 匹配目标 path，返回其 meta
    if (fullPath === targetPath) {
      return route.meta;
    }

    // 如果当前路由有子路由，递归查找
    if (route.children) {
      const meta = findMetaByPath(targetPath, fullPath, route.children);
      if (meta) {
        return meta;
      }
    }
  }

  // 如果没有找到匹配的路由，返回 undefined
  return undefined;
}